package com.ziyucoding.springboot.labs.lab4.concurrentdemo.example.atomic;

import com.ziyucoding.springboot.labs.lab4.concurrentdemo.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * Atomic 示例5
 *
 * @author ziyucoding
 * @date 2022-10-25
 **/
@Slf4j
@ThreadSafe
public class AtomicExample5 {

    private static AtomicIntegerFieldUpdater<AtomicExample5> updater = AtomicIntegerFieldUpdater.newUpdater(AtomicExample5.class, "count");

    /**
     * 计数
     */
    private volatile int count = 100;

    public int getCount() {
        return count;
    }

    public static void main(String[] args) {
        AtomicExample5 example = new AtomicExample5();
        if (updater.compareAndSet(example, 100, 168)) {
            // update success 1, 168
            log.info("update success 1, {}", example.getCount());
        }

        if (updater.compareAndSet(example, 120, 189)) {
            log.info("update success 2, {}", example.getCount());
        } else {
            // update failed, 168
            log.info("update failed, {}", example.getCount());
        }
    }
}
